var chokidar = require('chokidar');
var ws = require("nodejs-websocket");
var exec = require('child_process').exec;

var options = JSON.parse(process.argv[2] || "{}");
var workdir = options.workdir || "";
if (!workdir) {
    console.log("工作目录不能为空");
    return;
}

// 指定工作目录
var listenWorkdir = workdir;
if (options.suffixlist && options.suffixlist !== '*') {
    var tempArr = [];
    options.suffixlist.split(/\,/).forEach(function (value, index) {
        tempArr.push(workdir + "**/*." + value);
    });
    listenWorkdir = tempArr;
}

// 创建Websocket服务端
var server = ws.createServer(function (conn) {
    console.log("客户端建立连接");
    conn.on("close", function (code, reason) {
        console.log("客户端连接关闭")
    })
    conn.on("error", function (e) {
        console.log("客户端异常关闭")
    })
}).on("error", (e) => {
    if (e.code === 'EADDRINUSE') {
        console.log("Websocket服务端口(" + options.port + ")已被占用");
        process.exit();
    } else {
        console.log(e);
    }
}).on("listening", (e) => {
    console.log("Websocket服务已启动");
}).listen(options.port);

// 发送刷新消息到客户端
var st, stn;
var sendReloadAction = function () {
    clearTimeout(st);
    st = setTimeout(() => {
        server.connections.forEach(function (conn) {
            conn.sendText(JSON.stringify({action: "reload"}));
        });
    }, 200);
}

// 添加工作目录观察
chokidar.watch(listenWorkdir, {
    ignored: options.ignored,
    ignoreInitial: true,
    cwd: workdir
}).on('all', (event, path) => {
    console.log(event, path);
    var matches = path.match(/^addons\/([a-z]+)\//);
    if (matches && options.autoenableaddon === "1" && event !== 'unlink') {
        clearTimeout(stn);
        stn = setTimeout(() => {

            console.log("启用插件(" + matches[1] + ")");

            // 执行启用插件
            exec('cd ' + workdir + ';php think addon -a ' + matches[1] + ' -c enable -f 1', function (err, stdout, stderr) {
                if (err) {
                    console.log("发生错误:", err);
                }
                console.log("enabled...");
                sendReloadAction();
            });
        }, 100);
    } else {
        sendReloadAction();
    }
});